<?php


namespace app\jwt;


use Firebase\JWT\Key;
use think\Exception;

class Jwt
{
    //生成token
    public static function createJwt($userId = 'zq')
    {
        $key = md5('zq8876!@!'); //jwt的签发密钥，验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $time + 14400; //过期时间
        $token = array(
            "user_id" => $userId,
            "iss" => "http://www.najingquan.com/",//签发组织
            "aud" => "zhangqi", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = \Firebase\JWT\JWT::encode($token, $key,'HS256');
        return $jwt;
    }
    //校验jwt权限API
    public static function verifyJwt($jwt = '')
    {
        $key = md5('zq8876!@!');
        try {
            $jwtAuth = json_encode(\Firebase\JWT\JWT::decode($jwt, new Key($key,'HS256')));
            $authInfo = json_decode($jwtAuth, true);

            $msg = [];
            if (!empty($authInfo['user_id'])) {
                $msg = [
                    'status' => 1001,
                    'msg' => 'Token验证通过'
                ];
                return $authInfo['user_id'];
            } else {
                throw new Exception('Token验证不通过,用户不存在');
//                $msg = [
//                    'status' => 1002,
//                    'msg' => 'Token验证不通过,用户不存在'
//                ];
            }
        }  catch (\Firebase\JWT\ExpiredException $e) {
            throw new Exception('Token过期');
//            exit;
        } catch (\Exception $e) {
            throw new Exception('Token无效');
        }
    }
}